package com.sgb.kjwl.view.ui.activity.manage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteAddAddressBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.manage.CompanyAndDeptEntity;
import com.sgb.link.entity.WebSiteAddressEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.manage.WebsiteAddressModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class WebSiteAddAddressActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    @Inject
    WebsiteAddressModel mModel;
    private ActivityWebsiteAddAddressBinding mBinding;
    private static final String KEY_ENTITY = "key_entity";
    private static final String KEY_SITE_TYPE = "key_site_type";
    private WebSiteAddressEntity mEntity;
    private int mSiteType; //网站类型, 1 企业 2 团队0 个人
    private WebSiteAddressEntity mUserAddressEntity = new WebSiteAddressEntity();

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> addressEntityList = new ArrayList<>();
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity<Object>>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity<Object>>>> opt3;
    //城市列表
//    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity<Object>>> areaList;
    //公司列表
    private List<CompanyAndDeptEntity> mCompanyList = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    private String mAreaCode;
    private boolean isNewAddress;

    private CityPickView cityOption;

    private OptionsPickerView businessOption;



    //新增
    public static void launchForResult(Activity activity, int siteType, int requestCode){
        Intent intent = new Intent(activity, WebSiteAddAddressActivity.class);
        intent.putExtra(KEY_SITE_TYPE, siteType);
        activity.startActivityForResult(intent, requestCode);
    }
    //编辑
    public static void launchForResult(Activity activity, WebSiteAddressEntity entity, int siteType, int requestCode){
        Intent intent = new Intent(activity, WebSiteAddAddressActivity.class);
        intent.putExtra(KEY_ENTITY, entity);
        intent.putExtra(KEY_SITE_TYPE, siteType);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(new EnterpriseManageModule()).build().inject(this);
    }


    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        if (getIntent() != null) {
            mEntity = (WebSiteAddressEntity) getIntent().getSerializableExtra(KEY_ENTITY);
            mSiteType = getIntent().getIntExtra(KEY_SITE_TYPE, 1);
        }
        mBinding.itvCName.setVisibility(mSiteType == 1 ? View.VISIBLE : View.GONE);
        mBinding.itemName.setLabelName(mSiteType == 1 ? "联系人" : "收货人");
        mBinding.itemName.setLabelHint(mSiteType == 1 ? "请输入联系人姓名" : "请输入收货人姓名");
        isNewAddress = mEntity == null;
        if (isNewAddress) {
            mBinding.include.titleView.setText("新增地址");
            mBinding.include.rightView.setVisibility(View.GONE);
        } else {
            mBinding.include.titleView.setText("编辑地址");
            mBinding.include.rightView.setVisibility(View.VISIBLE);
            mModel.getDetailAddressById(this, "" + mEntity.getId());
            mUserAddressEntity = mEntity;
            showAddress(mUserAddressEntity);
        }
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_add_address);
        mBinding.itemLocate.setOnWholeItemClickListener(this);
        mBinding.include.ivBack.setOnClickListener(this);
        mBinding.itemPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itemZip.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.tvCommit.setOnClickListener(this);
        mBinding.include.rightView.setText("删除地址");
        mBinding.include.rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(mUserAddressEntity);
            }
        });
        mBinding.itvCName.setOnWholeItemClickListener(new ItemInputTextView.OnWholeItemClickListener() {
            @Override
            public void OnWholeItemClick(View view) {
                //企业列表
                if (mCompanyList.isEmpty()){
                    mModel.getCompanyList();
                } else {
                    showCompanys();
                }
            }
        });
        mModel.getMAllAddress().observe(this, new Observer<ArrayList<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>>>() {
            @Override
            public void onChanged(ArrayList<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> addressEntities) {
                if (!addressEntities.isEmpty()){
                    initAddressData(addressEntities);
                }
            }
        });
        mModel.getMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)){ //不管更新或者刪除都更新列表
                   MToast.showToast(WebSiteAddAddressActivity.this, s);
                   setResult(RESULT_OK);
                   finish();
                }
            }
        });
        mModel.getMCompanys().observe(this, companyAndDeptEntities -> {
            mCompanyList.clear();
            if (companyAndDeptEntities != null){
                mCompanyList.addAll(companyAndDeptEntities);
                showCompanys();
            }
        });
    }

    /**
     * 数据回显
     * @param data
     */
    public void showAddress(WebSiteAddressEntity data) {
        mAreaCode = data.getAreaNo();
        mBinding.itemName.setContent(data.getReceivePerson());
        mBinding.itemPhone.setContent(data.getPhone());
        mBinding.etDetail.setText(data.getDetailAddress());
        mBinding.itemLocate.setContent(data.getProvince() + data.getCity() + data.getArea());
        mBinding.switchDefault.setChecked(data.isDefaultAddress());
        mBinding.itvCName.setContent(data.getCompanyName());
        mBinding.itemZip.setContent(data.getPostalCode());
    }

    //企业下一二级公司列表
    public void showCompanys(){
        if (mCompanyList.isEmpty()) return;
        if (businessOption == null){
           businessOption = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
               @Override
               public void onOptionsSelect(int options1, int options2, int options3, View v) {
                   mBinding.itvCName.setContent(mCompanyList.get(options1).getName());
                   mUserAddressEntity.setDepartmentId(mCompanyList.get(options1).getId());
                   mUserAddressEntity.setNo(mCompanyList.get(options1).getComNo());
                   mUserAddressEntity.setCompanyName(mCompanyList.get(options1).getName());
               }
           }).setCancelText("取消").setSubCalSize(15)
                   .setCancelColor(getResources().getColor(R.color.color_tab_two))
                   .setTitleText("请选择公司")
                   .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                   .setSubmitText("确定")
                   .setSubmitColor(getResources().getColor(R.color.color_main))
                   .build();
        }
        businessOption.setPicker(mCompanyList);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_commit:
                if (mSiteType == 1 && TextUtils.isEmpty(mBinding.itvCName.getContent())) {
                    MToast.showToast(WebSiteAddAddressActivity.this, "请选择企业名称");
                    return;
                }
                if (TextUtils.isEmpty(mBinding.itemName.getContent())) {
                    MToast.showToast(WebSiteAddAddressActivity.this, mBinding.itemName.getHint());
                    return;
                }
                if (TextUtils.isEmpty(mBinding.itemPhone.getContent())){
                    MToast.showToast(WebSiteAddAddressActivity.this, "请输入联系号码");
                    return;
                }
                if (!CheckUtils.isMobileNum(mBinding.itemPhone.getContent())) {
                    MToast.showToast(WebSiteAddAddressActivity.this, "请输入正确的联系号码");
                    return;
                }
                if (TextUtils.isEmpty(mBinding.itemLocate.getContent())) {
                    MToast.showToast(WebSiteAddAddressActivity.this, "请选择收货地址");
                    return;
                }
                if (TextUtils.isEmpty(mBinding.etDetail.getText())) {
                    MToast.showToast(WebSiteAddAddressActivity.this, "请输入详细地址");
                    return;
                }
                mUserAddressEntity.setReceivePerson(mBinding.itemName.getContent());
                mUserAddressEntity.setPhone(mBinding.itemPhone.getContent());
                mUserAddressEntity.setAreaNo(mAreaCode);
                mUserAddressEntity.setDetailAddress(mBinding.etDetail.getText().toString());
                mUserAddressEntity.setStatus(mBinding.switchDefault.isChecked() ? "1" : "0");
                mUserAddressEntity.setPostalCode(mBinding.itemZip.getContent());
                mUserAddressEntity.setSiteType(mSiteType);

                mModel.saveOrUpdateAddress(WebSiteAddAddressActivity.this, mUserAddressEntity, true);
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_locate:
                if (!addressEntityList.isEmpty()) {
                    showCityPop();
                } else {
                    mModel.getAddressModel(this);
                }
                break;
        }
    }

        private void showDialog(WebSiteAddressEntity addressEntity) {
            View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
            final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
            roundCornerDialog.show();
            roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
            //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失

            TextView tv_message = view.findViewById(R.id.tv_message);
            TextView tv_title = view.findViewById(R.id.tv_title);
            TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
            TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
            tv_title.setText("删除地址");
            tv_title.setVisibility(View.VISIBLE);
            tv_message.setText("确定要删除地址吗");
            //确定
            tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //请求接口
//                deletePerson.put("id", id);
                    if (addressEntity.getSiteType() != null) {
                       //if (addressEntity.getSiteType() == 0){
                           mModel.bathDel(WebSiteAddAddressActivity.this, "" + addressEntity.getId());
                       //} else if (addressEntity.getSiteType() == 1){
                           //mModel.companyAddressDel(WebSiteAddAddressActivity.this, "" + addressEntity.getId());
                       //}
                    }
                    //mModel.bathDel(WebSiteAddAddressActivity.this, addressEntity.getId());
                    roundCornerDialog.dismiss();
                }
            });
            //取消
            tv_logout_cancel.setTextColor(getResources().getColor(R.color.color_333333));
            tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    roundCornerDialog.dismiss();
                }
            });
        }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> datas) {
        this.addressEntityList.clear();
        addressEntityList.addAll(datas);
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

            if (!isNewAddress) {
                if (addressEntityList.get(i).getId().equals(mUserAddressEntity.getProvinceNo())) {
                    cityPosition1 = i;
                }
            }

//            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                if (!isNewAddress) {
                    if (addressEntityList.get(i).getChildren().get(j).getId().equals(mUserAddressEntity.getCityNo())) {
                        cityPosition2 = j;
                    }
                }
                List<AddressEntity<Object>> cityAreaList = new ArrayList<>();
                List<AddressEntity<Object>> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                    if (!isNewAddress) {
                        for (int k = 0; k < children.size(); k++) {
                            if (children.get(k).getId().equals(mUserAddressEntity.getAreaNo())) {
                                cityPosition3 = k;
                            }
                        }
                    }
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    private void showCityPop() {
        if (cityOption == null) {
            cityOption = new CityPickBuilder(WebSiteAddAddressActivity.this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    String areaName;
                    if (opt3.get(options1).get(options2).get(options3) == null) {
                        areaName = "";
                    } else {
                        areaName = opt3.get(options1).get(options2).get(options3).getName();
                        mAreaCode = opt3.get(options1).get(options2).get(options3).getNo();
                        cityPosition3 = options3;
                        mUserAddressEntity.setArea(areaName);
                        mUserAddressEntity.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                    }
                    String content = addressEntityList.get(options1).getName() + opt2.get(options1).get(options2).getName() + areaName;
                    mBinding.itemLocate.setContent(content);
                    cityPosition1 = options1;
                    cityPosition2 = options2;
                    mUserAddressEntity.setProvince(addressEntityList.get(options1).getName());
                    mUserAddressEntity.setProvinceNo(addressEntityList.get(options1).getId());
                    mUserAddressEntity.setCity(opt2.get(options1).get(options2).getName());
                    mUserAddressEntity.setCityNo(opt2.get(options1).get(options2).getNo());
                }
            }).setCancelText("取消").setSubCalSize(15)
                    .setCancelColor(getResources().getColor(R.color.color_tab_two))
                    .setSubmitText("确定")
                    .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        }
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }
}
